<template>
  <div class="body">
    <div class="editAlert" v-if="editPop">
      <div class="Pop_title">
        编辑
      </div>
      <div class="formBox">
        <el-form label-width="130px" :model="editForm" ref="formRef" class="edit_form" :rules="editFormRoules">
          <div class="alert_content">
            <div class="Pop_half">
              <el-form-item label="景区名称" label-position="left" prop="title">
                <el-input v-model.trim="editForm.title" placeholder="请输入景区名称" class="search_input" clearable />
              </el-form-item>
              <el-form-item label="景区评分" label-position="left" prop="score">
                <el-rate v-model.trim="editForm.score" />
              </el-form-item>
              <el-form-item label="景区分类" label-position="left" prop="classid">
                <el-select v-model.trim="editForm.classid" placeholder="请选择分类" class="search_input">
                  <el-option v-for="item in typeList" :key="item.id" :label="item.title" :value="item.id" clearable />
                </el-select>
              </el-form-item>
              <el-form-item label="景区荣誉" label-position="left" prop="honor">
                <el-input v-model.trim="editForm.honor" placeholder="请输入店铺名誉" class="search_input" clearable />
              </el-form-item>
              <el-form-item label="景区电话" label-position="left" prop="tel">
                <el-input v-model.trim="editForm.tel" placeholder="请输入店铺电话" class="search_input" clearable />
              </el-form-item>
              <el-form-item label="营业时间" label-position="left" prop="starttime">
                <el-time-picker v-model.trim="editForm.starttime" placeholder="Arbitrary time" />
              </el-form-item>
              <el-form-item label="景区图片" label-position="left" prop="image">
                <div class="avatar-uploader">
                  <el-upload action="#" list-type="picture-card" :auto-upload="false" :limit="1"
                    :on-change="handleFileChange" :on-remove="handleRemove" :on-preview="handleimgsPreview"
                    :file-list="fileimg" :class="{ 'hide-upload': fileimg.length > 0 }">
                    <template v-if="fileimg.length === 0">
                      <el-icon>
                        <Plus />
                      </el-icon>
                    </template>
                    <template v-else>
                      <img class="avatar" :src="fileimg[0].url" alt="头像" />
                      <span class="avatar-actions">
                        <span class="avatar-delete" @click.stop="handleRemove(fileimg[0])">
                          <el-icon>
                            <Delete />
                          </el-icon>
                        </span>
                      </span>
                    </template>
                  </el-upload>
                </div>
              </el-form-item>
              <el-form-item label="人均价格" label-position="left" prop="price">
                <el-input-number v-model.trim="editForm.price" :min="1" />
              </el-form-item>
            </div>
            <div class="Pop_half">
              <el-form-item label="店铺轮播" label-position="left" prop="banner">
                <el-upload v-model:file-list="fileimgs" :on-change="FileimgsChange"
                  action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" list-type="picture-card"
                  :on-preview="handleimgsPreview" :on-remove="imgsRemove" :auto-upload="false" :limit="3">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>
                <el-dialog v-model="imgsState">
                  <img w-full :src="dialogImageUrl" alt="Preview Image" class="preview-img" />
                </el-dialog>
              </el-form-item>
              <el-form-item label="景区地址" label-position="left" prop="address">
                <el-input v-model.trim="editForm.address" placeholder="请输入景区地址" class="search_input" clearable />
              </el-form-item>
              <el-form-item label="经度" label-position="left" prop="lng">
                <el-input v-model.trim="editForm.lng" placeholder="请输入店铺经度" class="search_input" disabled="true" />
              </el-form-item>
              <el-form-item label="维度" label-position="left" prop="lat">
                <el-input v-model.trim="editForm.lat" placeholder="请输入店铺维度" class="search_input" disabled="true" />
              </el-form-item>
              <el-form-item label="景区搜索" label-position="left">
                <el-input v-model.trim="input" placeholder="请输入景区名称" class="search_input" id="address_input" />
              </el-form-item>
              <container class="map_container" style="height: 240px;" v-model:latitude="editForm.lat"
                v-model:longitude="editForm.lng" ref="mapRef" @update:address="handleAddressUpdate" />
            </div>
          </div>
          <el-form-item label="景区介绍" label-position="left" prop="content">
            <UEditor v-model.trim="editForm.content" @update:modelValue="EditorInput" />
          </el-form-item>
        </el-form>
      </div>
      <div class="footer_btn">
        <el-button type="primary" @click="affirm(formRef)">确认</el-button>
        <el-button class="rigthBtn" @click="editPop = false">取消</el-button>
      </div>
    </div>
    <div class="content" v-if="!editPop">
      <div class="search_box">
        <el-form label-width="auto" :model="search" class="search_form">
          <el-form-item label="店铺名称" label-position="top">
            <el-input v-model="search.title" placeholder="请输入店铺名称" class="search_input input_height"
              @input="searchData" />
          </el-form-item>
          <el-form-item label="上架/下架" label-position="top">
            <el-select v-model="search.state" placeholder="请选择店铺状态" size="default" class="search_input"
              @change="searchData" clearable>
              <el-option label="下架" value="2" />
              <el-option label="上架" value="1" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="line"></div>
      <el-table :data="pageCount" style="width: 100%">
        <el-table-column prop="title" label="景区名称" align="center" />
        <el-table-column prop="title" label="景区状态" align="center">
          <template #default="scope">
            <el-switch @change="changeStatus(scope.row)" v-model="scope.row.state" active-value="1"
              inactive-value="2" />
          </template>
        </el-table-column>
        <el-table-column label="图片" align="center" width="80">
          <template #default="scope">
            <div class="demo-image__preview">
              <el-image style="width: 40px; height: 40px"
                :src="scope.row.image.startsWith('http') ? scope.row.image : url + scope.row.image" :zoom-rate="1.2"
                :max-scale="7" :min-scale="0.2"
                :preview-src-list="[scope.row.image.startsWith('http') ? scope.row.image : url + scope.row.image]"
                show-progress fit="cover" preview-teleported />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="景区地址" align="center" width="250">
          <template #default="scope">
            <p class="introduce">{{ scope.row.address }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="tel" label="景区电话" align="center" />
        <el-table-column prop="createtime" label="创建时间" align="center" />
        <el-table-column prop="createtime" label="操作" align="center">
          <template #default="scope">
            <p @click="handleEdit(scope.row); editPop = true;" class="edit">编辑</p>
          </template>
        </el-table-column>
      </el-table>
      <div class="custom_container">
        <el-pagination @size-change="pageNum" @current-change="pageChange" :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]" :page-size="pageSize" layout="sizes, prev, pager, next, jumper"
          :total="pageData.length" class="custom_pagination" />
      </div>

    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { getPlayScenicList, addPlayScenic, statusPlayScenic } from '/@/api/scenic/scenic_goods/index';
import { foodTypeList } from '/@/api/scenic/scenic_class/index';
import { fileUpload } from '/@/api/login';
import { url } from '/@/api/url';
import { ElMessage, FormInstance, FormRules, UploadFile } from 'element-plus';
import container from '/@/components/map/MapContainer.vue';
import { debounce } from 'lodash-es';
import UEditor from '/@/components/UEeditor/index.vue'

const input = ref('');
const mapRef = ref(null);

// 定义数据类型
interface FoodType {
  id: number;
  title: string;
  state: number | string;
}
// 分页页数
const currentPage = ref(1);
// 一页的数据
const pageSize = ref(10);
const data = ref<FoodType[]>([]);
const pageData = ref<FoodType[]>([]);
const typeList = ref<FoodType[]>([]);
const editPop = ref(false);
const formRef = ref<FormInstance>();
const imgsState = ref(false);
const search = reactive({
  title: '',
  state: '',
})

const editForm = reactive({
  id: '',
  title: '',
  image: '',
  banner: [] as string[],
  score: 1,
  honor: '',
  address: '',
  lng: 0 as number,
  lat: 0 as number,
  tel: '',
  content: '',
  price: '',
  classid: '',
  starttime: '',
  state: 1,
  user_id: '',
})


const editFormRoules = reactive<FormRules>({
  title: [{ required: true, message: '请输入店铺名称', trigger: ['change', 'blur'] },],
  score: [{ required: true, message: '请选择评分', trigger: ['change', 'blur'] },],
  classid: [{ required: true, message: '请选择分类', trigger: ['change', 'blur'] },],
  tel: [{ required: true, message: '请输入手机号', trigger: ['change', 'blur'] },
  { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: ['change', 'blur'] }],
  starttime: [{ required: true, message: '请选择营业时间', trigger: ['change', 'blur'] },],
  image: [{ required: true, message: '请上传图片', trigger: ['change', 'blur'] }],
  info: [{ required: true, message: '请输入简介', trigger: ['change', 'blur'] },],
  banner: [{ required: true, message: '请上传轮播图', trigger: ['change', 'blur'] }],
  honor: [{ required: true, message: '请输入获得的荣誉', trigger: ['change', 'blur'] }],
  address: [{ required: true, message: '请输入景区地址', trigger: ['change', 'blur'] }],
  lng: [{ required: true, message: '选择经度', trigger: ['change', 'blur'] }],
  lat: [{ required: true, message: '选择维度', trigger: ['change', 'blur'] }],
  content: [{ required: true, message: '请输入景区详情', trigger: ['change', 'blur'] }],
})

// 页面列表接口
const getList = () => {
  getPlayScenicList({ userid: JSON.parse(localStorage.getItem('userinfo') || '').userinfo.id }).then((res) => {
    console.log(res);
    data.value = res.data;
    pageData.value = res.data;
  }).catch((error) => {
    console.log(error);
  });
}
getList();

// 分类接口
foodTypeList({ userid: JSON.parse(localStorage.getItem('userinfo') || '').userinfo.id }).then((res) => {
  typeList.value = res.data;
}).catch((error) => {
  console.log(error);
});

// 计算当前页码的起始索引和结束索引，并返回对应区间的数据
const pageCount = computed(() => {
  // 计算起始索引，基于当前页码和每页大小
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return pageData.value.slice(start, end);
});
/* 分页改变 */
const pageChange = (val: number) => {
  currentPage.value = val;
};
/* 分页大小改变 */
const pageNum = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
};
// 编辑显示
const handleEdit = async (item: any) => {
  editPop.value = true;
  const date = new Date();
  fileimgs.value = item.banner.split(',')?.map((imgPath: string, index: number) => ({
    uid: `img-${Date.now()}-${index}`,       // 生成唯一ID
    name: imgPath.split('/').pop() || `image-${index}.jpg`, // 提取文件名
    status: 'success',                       // 标记为已上传成功
    url: `${imgPath.startsWith('http') ? imgPath : url + imgPath}`,
    response: { data: { url: imgPath } }     // 保留原始路径
  })) || [];
  editForm.price = item.price;
  editForm.state = item.state;
  editForm.id = item.id;
  editForm.title = item.title;
  editForm.score = item.score;
  editForm.classid = item.classid;
  editForm.starttime = item.starttime;
  editForm.tel = item.tel;
  editForm.honor = item.honor;
  editForm.address = item.address;
  editForm.lng = item.lng;
  editForm.lat = item.lat;
  editForm.tel = item.tel;
  editForm.content = item.content;
  editForm.image = item.image;
  editForm.banner = item.banner.split(',').map((imgPath: string, index: number) => (imgPath.startsWith(url) ? imgPath : url + imgPath));
  const img = item.image.startsWith(url) ? item.image : url + item.image;
  fileimg.value = img
    ? [
      {
        uid: Date.now(),
        name: 'avatar',
        url: img,
        status: 'success',
      },
    ]
    : [];
}

// 图片上传
const fileimg = ref<UploadFile[]>([])  // 关键：维护文件列表
// 图片预览的路径
const dialogImageUrl = ref(<any>[]);
// 图片上传
const handleFileChange = async (file: UploadFile) => {
  // 创建本地预览
  file.url = URL.createObjectURL(file.raw!);
  fileimg.value = [file];
  // 上传到服务器
  const formData = new FormData();
  formData.append('file', file.raw!);
  console.log(formData);
  fileUpload(formData).then(res => {
    editForm.image = res.data.url;
    formRef.value?.clearValidate('img');
  }).catch((error) => {
    fileimg.value = [];
    editForm.image = '';
    ElMessage.error('上传失败');
    handleRemove();
    formRef.value?.validateField('img');
  });
}
// 图片删除
const handleRemove = (file?: UploadFile) => {
  fileimg.value = [];
  editForm.image = '';
  formRef.value?.validateField('img');
};

// 多图上传的监听
const fileimgs = ref<UploadFile[]>([]);
const FileimgsChange = async (file: UploadFile) => {
  // 1. 创建本地预览
  file.url = URL.createObjectURL(file.raw!);
  file.status = 'uploading';
  fileimgs.value.push(file);
  const formData = new FormData();
  formData.append('file', file.raw!);
  try {
    const res = await fileUpload(formData);
    if (res.code === 1) {
      const serverUrl = res.data.url; // 假设返回结构为 { data: { url: string } }
      const index = fileimgs.value.findIndex(item => item.uid === file.uid);
      if (index !== -1) {
        fileimgs.value[index] = {
          ...file,
          status: 'success',
          url: url + serverUrl, // 显示服务器URL（替换本地预览URL）
          response: res
        };
      }
      editForm.banner.push(serverUrl);
      formRef.value?.validateField('imgs');
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.log(error);
    // 5. 标记失败状态
    const index = fileimgs.value.findIndex(item => item.uid === file.uid);
    if (index !== -1) fileimgs.value[index].status = 'fail';
    ElMessage.error('上传失败');
  }
};
// 多图删除图片
const imgsRemove = (file: UploadFile) => {
  // 1. 从界面列表中删除
  fileimgs.value = fileimgs.value.filter(item => item.uid !== file.uid);
  // 2. 从表单数据中删除对应的URL
  if (file.url) {
    editForm.banner = editForm.banner.filter(url => url !== file.url);
    formRef.value?.validateField('imgs');
  } else if (file.url?.startsWith('http')) {
    // 处理未成功上传但已添加本地预览的情况
    editForm.banner = editForm.banner.filter(url => url !== file.url);
    formRef.value?.validateField('imgs');
  }
  formRef.value?.validateField('imgs');
};
// 图片预览
const handleimgsPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url; // 优先显示服务器URL
  imgsState.value = true;
};
// 确认编辑事件
const affirm = async (formEl: FormInstance | undefined) => {
  for (let i in data.value) {
    if (data.value[i].title == editForm.title && !editForm.id) {
      return ElMessage.warning('名称已存在');
    }
  }
  await formEl?.validate((valid, fields) => {
    if (valid) {
      addPlayScenic({
        id: editForm.id,
        title: editForm.title,
        image: editForm.image,
        banner: editForm.banner.join(','),
        score: editForm.score,
        honor: editForm.honor,
        address: editForm.address,
        lng: editForm.lng,
        lat: editForm.lat,
        tel: editForm.tel,
        content: editForm.content,
        price: editForm.price,
        classid: editForm.classid,
        starttime: editForm.starttime,
        state: editForm.state,
        user_id: JSON.parse(localStorage.getItem('userinfo') || '').userinfo.id,
      }).then((res) => {
        console.log(res);
        ElMessage({
          message: '编辑成功',
          type: 'success',
        })
        editPop.value = false;
        getList();
      }).catch((error) => {
        console.log(error);
      });
    }
  })
}

const changeStatus = debounce((item: any) => {
  statusPlayScenic({
    id: item.id,
    state: item.state
  }).then((response) => {
    console.log(response);

    console.log('触发');
    if (response.code === 1) {
      ElMessage.success(response.msg);
      formRef.value?.resetFields();
      getList();
    }
  }).catch((error) => {
    console.error('请求失败:', error);
  });
}, 1000);

// 富文本的监听事件
const EditorInput = () => {
  if (editForm.content.trim()) {
    formRef.value?.clearValidate('content');
  } else {
    formRef.value?.validateField('content');
  }
};

// 搜索函数
const searchData = () => {
  pageData.value = data.value;
  const filteredData = () => {
    // 无搜索词时返回全部数据
    if (search.title == '' && search.state === undefined) {
      return (pageData.value = data.value);
    }
    return pageData.value.filter((item) => {

      // 检查每个字段是否满足相应条件（如果该搜索条件存在）
      const nameMatch = !search.title || (item.title && item.title.toString().toLowerCase().includes(search.title.toLowerCase()));
      const nameState = !search.state || (item.state == search.state);
      return nameMatch && nameState;
    });
  };
  pageData.value = filteredData();
};

const handleAddressUpdate = (val: any) => {
  input.value = val; // 接收子组件传递的地址
};

</script>

<style scoped>
.content {
  position: relative;
  padding: 50px;
  margin: 2%;
  background-color: white;
}

.line {
  width: 100%;
  height: 1px;
  margin: 25px 0;
  background-color: #e8e7e7;
}

.search_form {
  width: 100%;
  display: flex;
  margin-bottom: -22px;
}

.search_input {
  width: 240px;
  margin-right: 30px;
}

.input_height {
  height: 33px;
}

.button_height {
  height: 33px;
}

.introduce {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

.custom_container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}

.edit {
  color: #409EFF;
  cursor: pointer;
}

.editAlert {
  position: absolute;
  width: 100%;
  overflow: auto;
  background-color: white;
  top: 0;
  right: 0;
  z-index: 30;
}

.edit_form {
  width: 80%;
  margin: 0 auto;
  margin-top: 2%;
}

.Pop_title {
  padding: 2%;
  border-bottom: 1px solid #ddd;
}

.alert_content {
  display: flex;
  justify-content: space-between;
}

.footer_btn {
  display: flex;
  justify-content: end;
  margin-top: 5%;
  margin-right: 5%;
  margin-bottom: 5%;
}

.rigthBtn {
  margin-left: 5%;
}



.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader {
  position: relative;
  display: inline-block;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

/* 隐藏上传按钮当有图片时 */
.hide-upload :deep(.el-upload) {
  display: none;
}

/* 在全局或组件样式添加 */
.avatar-uploader :deep(.el-upload-list__item) {
  transition: none !important;
}

.map_container {
  width: 240px;
  height: 180px;
}

.preview-img {
  width: 100%;
}
</style>